import { HttpClient } from '@angular/common/http';
import { Component, Input, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { Observable } from 'rxjs';
import { CommonService } from 'src/app/service/common/common.service';
import { MessageService } from 'src/app/service/message.service';
import { UsageCodeData, UserBindService } from 'src/app/service/user-bind.service';
import { NAME_REG } from 'src/app/utils/regExp';
import { dateFormat } from 'src/app/utils/utils';

@Component({
  selector: 'app-basic-live',
  templateUrl: './basic-live.component.html',
  styleUrls: ['./basic-live.component.scss']
})
export class BasicLiveComponent implements OnInit {

  constructor(
    private fb: FormBuilder,
    private http: HttpClient,
    private message: MessageService,
    private userBind: UserBindService,
    private common: CommonService
  ) { }

  ngOnInit() {
    this.common.setRightInfoVisible(true)
    this.initForm();
    this.initPage();
  }

  validateForm: FormGroup = new FormGroup({});
  initForm() {
    this.validateForm = this.fb.group({
      userCode: [''],
      usageCode: ['', [
        Validators.required, Validators.pattern(/^[0-9]\d{7}$/)
      ]],
      accountName: [''],
      address: [''],
      userNo: [],
      userName:  ['', [
        Validators.required, Validators.pattern(NAME_REG)
      ]],
      userAddr: ['', [
        Validators.required
      ]],
      applyUserTel: ['', [
        Validators.required,
        Validators.pattern(/^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/)
      ]],
      applyUserCerNum: ['', [
        Validators.required
      ]],
      businessType: [null, [
        Validators.required
      ]],
      baseLivingCode: ['', [
        Validators.required
      ]],
      startDate: ['', [
        Validators.required
      ]],
      applyReason: [''],
      endDate: ['', [
        Validators.required
      ]],
      file1: [''],
      file2: [''],
      file3: [''],
      // houseHold: [''],
      // waterPic: [''],
      infoSources:'WT',
      isSecret: true
    });

    this.basicLiveForm = this.fb.group({
      personNum: [],
      basicLiveInfo: this.fb.group({})
    });
  }

  @Input() basicLiveId = ''
  formAvailable = true
  initPage(){
    this._getBindList();
    this._getBasicLiveType();
    // 详情预览
    if(this.basicLiveId){
      const url = `/api/gsxmcp/cf/mg/v1.0/baseLiving/detail/${this.basicLiveId}`
      this.http.get(url).subscribe((res: any) => {
        console.log(res)
        res.usageCode = res.userCode
        this.validateForm.patchValue(res)

        let detailList = res.detailList;
        if(!(detailList && detailList.length > 0)) return 

        this.basicLiveForm.get('personNum')?.setValue(detailList.length)
        const details = {}
        for(let i = 0; i < detailList.length; i++){
          details[`name${i}`] = detailList[i]['name']
          details[`cardFile${i}`] = detailList[i]['cardFile']
          details[`certificateNumber${i}`] = detailList[i]['certificateNumber']
          // details[`certificateType${i}`] = detailList[i]['certificateType']
        }
        this.basicLiveForm.get('basicLiveInfo')?.patchValue(details);
        (this.basicLiveForm.get('basicLiveInfo') as FormGroup).disable()
      })

      this.validateForm.disable()
      this.basicLiveForm.disable();
      this.formAvailable = false
    }
  }

  usageCodeInfo: UsageCodeData[] = [];
  userCodeLoading = true;
  _getBindList(){  
    this.userBind._getBindList().subscribe(res => {
      this.usageCodeInfo = res;
      this.userCodeLoading = false;
    })
  }

  async onUsageCodeChange(userCode: string){
    this.validateForm.patchValue({
      userName: '',
      userAddr: '',
      accountName: '',
      address: '',
      userNo: '',
      userCode: ''
    })
    this.disableBtn = false
    // 用户编号校验
    const msg = await this.common.usageCodeValid('10', userCode)
    if(msg){
      this.message.error(msg)
      this.disableBtn = true
      return
    }

    let temp = this.usageCodeInfo.filter((item: any) => {
      return item.usageCode === userCode;
    })[0]
    if(!temp) return 
    this.validateForm.patchValue({
      userName: temp['accountName'],
      userAddr: temp['address'],
      accountName: temp['accountName'],
      address: temp['address'],
      userNo: {usageCode: userCode, address: temp['address']},
      userCode: userCode
    });
    
  }

  onDatePickerChange(value: string, controlName: any){
    // console.log(value, controlName);
    // this.validateForm.patchValue({
    //   controlName: this.util.dateFormat(value)
    // })
    // this.basicLiveForm.get('basicLiveInfo').get(controlName).setValue(this.util.dateFormat(value));
  }

  /************************* 动态添加表单字段 *************************/
  basicLiveForm: FormGroup = new FormGroup({});
  controlArray: Array<{ id: number; controlNames: any[] }> = [];
  personNumChange(e: number): void {
    const id = this.controlArray.length > 0 ? this.controlArray[this.controlArray.length - 1].id + 1 : 0;
    const controlArrayLen = this.controlArray.length;
    if(e > controlArrayLen){ // 增加的情况
      for(let i = 0; i < e - controlArrayLen; i++){
        const controlNames = [
          { label: '姓名', controlName: `name${id + i}`, type: 'input' },
          { label: '证件编号', controlName: `certificateNumber${id + i}`, type: 'input' },
          { label: '身份证明文件', controlName: `cardFile${id + i}`, type: 'upload' }
        ];

        controlNames.forEach(item => {
          const controlName = item.controlName;
          // const index = this.controlArray.push(control);
          (this.basicLiveForm.get('basicLiveInfo') as FormGroup ).addControl(
            controlName,
            new FormControl(null, Validators.required)
          );
        })
        
        this.controlArray.push({id: id + i, controlNames})
      }
    }
    if(e < controlArrayLen){ // 数字减少的情况
      for(let i = 0; i < controlArrayLen - e; i++){
        this.controlArray.pop();

        let index = controlArrayLen - 1 - i;
        const controlNames = [
          { label: '姓名', controlName: `name${id + i}`, type: 'input' },
          { label: '证件编号', controlName: `certificateNumber${id + i}`, type: 'input' },
          { label: '身份证明文件', controlName: `cardFile${id + i}`, type: 'upload' }
        ];

        controlNames.forEach(item => {
          const controlName = item.controlName;
          (this.basicLiveForm.get('basicLiveInfo') as FormGroup ).removeControl(controlName);
        })
      }
    }
  }
  removeBasicLiveInfo(item: { id: number; controlNames: Object[] }){
    if(this.basicLiveId) return;

    let indenx = this.controlArray.indexOf(item);
    this.controlArray.splice(indenx, 1);
    item.controlNames.forEach((e: any) => {
      (this.basicLiveForm.get('basicLiveInfo') as FormGroup ).removeControl(e.controlName);
    })
    this.basicLiveForm.patchValue({ personNum: this.controlArray.length })
    
  }
  /************************* 动态添加表单字段 end *************************/
  
  basicLiveTypeList: any = []
  basicLiveTypeLoading = false;
  _getBasicLiveType(){
    this.basicLiveTypeList = [
      {
          "code": "020701",
          "name": "首次申请",
          "id": "d3021fa5-f88d-471f-a346-abc756a680b2"
      },
      {
          "code": "020702",
          "name": "续期",
          "id": "09a7fc46-b310-4a7b-8247-73a99a95a578"
      },
      {
          "code": "020703",
          "name": "取消低保",
          "id": "1f0483c2-e5d6-4e8a-9080-b9f1bfc0c337"
      }
    ]
    // this.basicLiveTypeLoading = true;
    // this.getBasicLiveType().subscribe(res => {
    //   this.basicLiveTypeList = res;
    //   if(this.basicLiveId){
    //     this.onBasicLiveTypeChange(this.validateForm.get('businessType')?.value)
    //   }
    //   this.basicLiveTypeLoading = false;
    // })
  }
  cancelBasicLive = false;
  onBasicLiveTypeChange(value: string){
    const res: any = this.basicLiveTypeList.find((item: any) => item.id === value)
    if(!res) return
    if(res.name === '取消低保'){
      this.cancelBasicLive = true

      this.validateForm.get('baseLivingCode')?.clearValidators()
      this.validateForm.get('startDate')?.clearValidators()
      this.validateForm.get('endDate')?.clearValidators()
    }else{
      this.cancelBasicLive = false

      this.validateForm.get('baseLivingCode')?.setValidators(Validators.required)
      this.validateForm.get('startDate')?.setValidators(Validators.required)
      this.validateForm.get('endDate')?.setValidators(Validators.required)
    }
  }

  btnLoading = false;
  onSubmit(){
    console.log(this.validateForm.getRawValue())
    
    let controls = this.validateForm.controls;
    for (let i in controls) {
      controls[i].markAsDirty();
      controls[i].updateValueAndValidity();
    }
    
    for(let i in controls){
      if(controls[i].invalid){
        console.log(controls[i]);
        return ;
      }
    }

    if(!this.cancelBasicLive){
      if(this.basicLiveForm.get('personNum')?.value <= 0){
        this.message.info('需要补充低保人信息');
        return ;
      }
  
      let controls2 = (this.basicLiveForm.get('basicLiveInfo') as FormGroup).controls;
      for (let i in controls2) {
        controls2[i].markAsDirty();
        controls2[i].updateValueAndValidity();
      }
      for(let i in controls2){
        if(controls2[i].invalid){
          return ;
        }
      }
    }

    // 文件上传判空
    if(this.validateForm.get('file1')?.value === ''){
      this.message.info('请上传身份证明文件');
      return ;
    }
    // if(this.validateForm.get('file2').value === ''){
    //   this.util.info('请上传租赁合同文件');
    //   return ;
    // }
    if(!this.cancelBasicLive){
      if(this.validateForm.get('file3')?.value === ''){
        this.message.info('请上传低保三证文件');
        return ;
      }
    }
    

    // 提交
    let params = this.validateForm.getRawValue();
    params['startDate'] = dateFormat(params['startDate']);
    params['endDate'] = dateFormat(params['endDate']);
    params.personNum = this.basicLiveForm.get('personNum')?.value;
    params.detailList = this._getDetailList();
    
    console.log('params =======> ', params);
    
    this.addBasicLive(params);
  }
  _getDetailList(){
    let details = this.basicLiveForm.get('basicLiveInfo')?.value;
    console.log(details);
    let detailList = [];
    for(let i = 0; i < this.basicLiveForm.get('personNum')?.value; i++){
      if(details.hasOwnProperty(`name${i}`)){
        let detail = {};
        detail['name'] = details[`name${i}`]
        detail['certificateNumber'] = details[`certificateNumber${i}`];
        detail['cardFile'] = details[`cardFile${i}`];

        detailList.push(detail);
      }
    }
    console.log(detailList);
    

    return detailList;
  }


  // 文件上传回调接口
  uploadBack(fileId: string, fileName: string){
    if(this.validateForm.get(fileName)){
      this.validateForm.get(fileName)?.setValue(fileId);
    }else{
      (this.basicLiveForm.get('basicLiveInfo') as FormGroup).get(fileName)?.setValue(fileId);
    }
    
  }

  /************************* 接口 *************************/
  getBasicLiveType(): Observable<any>{
    let url = '/api/gsxmcp/cf/mg/v1.0/funcData/param/1'
    // let url = '/api/gsxmcp/bd/cm/v1.0/codeItems/D120'
    return this.http.get(url);
  }
  disableBtn = false
  addBasicLive(params: any){
    this.btnLoading = true;
    const url = '/api/gsxmcp/cf/mg/v1.0/baseLiving';
    this.http.post(url, params).subscribe(res => {
      this.message.success('提交成功');
      this.validateForm.disable();
      this.basicLiveForm.disable();
      (this.basicLiveForm.get('basicLiveInfo') as FormGroup).disable()
      this.disableBtn = true
      this.btnLoading = false;
    }, error => {
      console.log(error);
      this.btnLoading = false;
      this.message.createErrorMessage(error);
    })
  }
  /************************* 接口结束 *************************/
  onReset(){
    this.message.confirmModal('确定退出吗？退出将清空表单信息，并返回上一页！', () => {
      history.go(-1)
    })
  }

  doBack(){
    history.go(-1)
  }

  // 电子证照
  cardIdVerifyBtnBack(e: any, key: any, fieldKey: string){
    if(this.validateForm.get(fieldKey)){
      this.validateForm.get(key)?.setValue(e)
      this.validateForm.get(fieldKey)?.disable()
    }

    // if((this.basicLiveForm.get('basicLiveInfo') as FormGroup).get(fieldKey)){
    //   (this.basicLiveForm.get('basicLiveInfo') as FormGroup).get(key).setValue(e);
    //   (this.basicLiveForm.get('basicLiveInfo') as FormGroup).get(fieldKey).disable()
    // }
  }

}
